package com.zc.bigdata.yarn.v2;

import com.zc.bigdata.utils.LogParser;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * 省份访问统计
 */
public class ETLAPP {

    public static void main(String[] args) throws Exception {
        System.setProperty("hadoop.home.dir", "D://gitee//hadoop-2.6.0");
        Configuration configuration = new Configuration();
        Job job = Job.getInstance(configuration);

        job.setJarByClass(ETLAPP.class);
        job.setMapperClass(MyMapper.class);

        job.setMapOutputKeyClass(NullWritable.class);
        job.setMapOutputValueClass(Text.class);

        // 提前删除输入目录，以免运行报错
        FileUtils.deleteDirectory(new File("input//tracklog//etl"));

        // 设置输入文件夹和输出文件夹
        FileInputFormat.setInputPaths(job, new Path("input//tracklog//"));
        FileOutputFormat.setOutputPath(job, new Path("input//tracklog//etl"));

        // 执行job
        boolean result = job.waitForCompletion(true);
        System.out.println(result);

    }

    static class MyMapper extends Mapper<LongWritable, Text, NullWritable, Text> {

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            Map<String, String> resultMap = LogParser.parseLog(value.toString());
            String ip = StringUtils.isNotBlank(resultMap.get("ip")) ? resultMap.get("ip") : "-";
            String url = StringUtils.isNotBlank(resultMap.get("url")) ? resultMap.get("url") : "-";
            String sessionId = StringUtils.isNotBlank(resultMap.get("sessionId")) ? resultMap.get("sessionId") : "-";
            String time = StringUtils.isNotBlank(resultMap.get("time")) ? resultMap.get("time") : "-";
            String country = StringUtils.isNotBlank(resultMap.get("country")) ? resultMap.get("country") : "-";
            String province = StringUtils.isNotBlank(resultMap.get("province")) ? resultMap.get("province") : "-";
            String city = StringUtils.isNotBlank(resultMap.get("city")) ? resultMap.get("city") : "-";

            String stringBuilder = ip + "\t" +
                    url + "\t" +
                    sessionId + "\t" +
                    time + "\t" +
                    country + "\t" +
                    province + "\t" +
                    city + "\t";
            context.write(NullWritable.get(), new Text(stringBuilder));
        }
    }

}
